import { updateQueue } from './Component'

/**
 *给真实都没添加一个真实事件处理函数
 * @param {*} dom 真实dom
 * @param {*} eventType 事件类型
 * @param {*} listener 监听函数
 */
export function addEvent(dom, eventType, listener) {
  let store = dom.store || (dom.store = {}) //获取dom状态
  store[eventType] = listener
  if (!document[eventType]) {
    //当前事件在文档流哪里不存在的时候
    document[eventType] = dispatchEvent
  }
}

const syntheticEvent = {
  stopping: false,
  stopdefinedEvent() {
    this.stopping = true
  },
}
function dispatchEvent(event) {
  let { target, type } = event //事件源=button那个Dom 类型type=click
  let eventType = `on${type}` //开启批量更新
  updateQueue.isBatchingUpdate = true
  syntheticEvent = createSyntheticEvent(event)
  while (target) {
    //仿造事件冒泡
    let { store } = target
    let listener = store && store[eventType]
    listener && listener.call(target, syntheticEvent)
    if (stopping) break //是否开启冒泡
    target = target.parentNode
  }

  for (let key in syntheticEvent) {
    //清空dom 事件
    syntheticEvent[key] = null
  }
  updateQueue.batchUpdate()
}

function createSyntheticEvent(nactiveEvent) {
  for (let key in nactiveEvent) {
    syntheticEvent[key] = nactiveEvent[key]
  }

  return syntheticEvent
}
